<?php

namespace common\model\sell66;

use common\db\Sell66;

class UserBank extends Sell66 {
	protected $table = 'user_bank';
	protected $pk = 'user_bank_id';
	public static $currentActiveMap = array (
			"active" => 1,
			"disactive" => 0 
	);
	/**
	 * 保存用户自己的体现账号信息
	 * 
	 * @param unknown $userId        	
	 * @param unknown $realName        	
	 * @param unknown $account        	
	 * @param unknown $bankType        	
	 * @param unknown $bankName        	
	 * @return boolean
	 */
	public static function saveUserBank($userId, $realName, $account, $bankType, $bankName,$bankId) {
		$userBank = static::get ( [ 
				'user_id' => $userId,
				'real_name' => $realName,
				'account' => $account,
				'bank_type' => $bankType,
				'bank_name' => $bankName,
		] );
		$connection = (new self())->db();
		$connection->startTrans ();
		try {
			static::update ( [ 
					'current_active' => self::$currentActiveMap ['disactive'] 
			], [ 
					'user_id' => $userId 
			] );
			if ($userBank) {
				$userBank->current_active = self::$currentActiveMap ['active'];
				$userBank->bank_id = $bankId;
				$userBank->save ();
			} else {
				$userBank = new UserBank ();
				$userBank->user_id = $userId;
				$userBank->real_name = $realName;
				$userBank->account = $account;
				$userBank->bank_type = $bankType;
				$userBank->bank_name = $bankName;
				$userBank->bank_id = $bankId;
				$userBank->current_active = self::$currentActiveMap ['active'];
				$userBank->save ();
			}
			$connection->commit ();
			return $userBank->user_bank_id;
		} catch ( \Exception $e ) {
			$connection->rollback ();
			return false;
		}
	}
	public static function defaultWithdrawAccount($userId, $bankType) {
		$userBank = static::get ( [ 
				'user_id' => $userId,
				"bank_type" => $bankType,
				'current_active' => self::$currentActiveMap ['active'] 
		] );
		if (empty ( $userBank )) {
			$userBank = static::where ( [ 
					'user_id' => $userId,
					"bank_type" => $bankType 
			] )->order ( [ 
					'updated_time' => 'desc' 
			] )->find ();
		}
		return $userBank;
	}

	public static function getUserBankInfo($userId, $userBankId)
    {
        return static::get(['user_id'=>$userId, 'user_bank_id'=>$userBankId]);
    }

    /**
     * 根据账号，查询user_id信息
     * @param string $account 账号
     * @return bool
     */
    public static function getUserIdGroupAccount($account)
    {
    	$where = array(
    		'account' => $account,
    	);
    	return static::where($where)->field('user_id')->group('user_id')->select();
    }
}